package com.marquisx.tzdice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.marquisx.common.utils.StringUtils;
import com.marquisx.common.utils.TZUtils;
import com.marquisx.tzdice.model.DiceAction;
import com.marquisx.tzdice.model.DiceActionManager;

public class ActionEdit extends Activity implements OnClickListener, OnSeekBarChangeListener, OnCheckedChangeListener, OnItemSelectedListener
{
	private static final String TAG = "TZDice: ActionEdit";
	
	private LinearLayout basicContainer;
	private LinearLayout backgroundImageContainer;
	
	private DiceActionManager actionManager;
	private DiceAction action;
	
	private ImageButton actionPicIBtn;
	private TextView actionStatusTV;
	private EditText actionNameET;
	private EditText actionDescriptionET;
	private Spinner actionDiceSpinner;
	private SeekBar actionTimesSeekBar;
	private SeekBar actionOffsetSeekBar;
	private CheckBox actionHasThresholdCB;
	private SeekBar actionThresholdSeekBar;
	
	private Button actionSaveBtn;
	private Button actionCancelBtn;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		actionManager = DiceActionManager.getInstance(this);
		
		long actionId = getSharedPreferences(Constants.PREF, 0)
							.getLong(Constants.SELECTED_ACTION_ID, Constants.NEW_ACTION_ID);
		if( actionId != Constants.NEW_ACTION_ID )		//-1
		{
			action = actionManager.getAction(actionId);
		}
		else
		{
			action = new DiceAction();
			action.setPictureId(Constants.DEF_PIC_ID);
			action.setDice(Setting.getDefaultDice(this));
		}
		
		if (null != action)
		{
			getSharedPreferences(Constants.PREF, 0)
				.edit()
				.putInt(Constants.SELECTED_PIC_ID, action.getPictureId())
				.commit();
		}
		
		setContentView(R.layout.action_edit);
		findViews();
		setListeners();
		prepareViews();
		refresh();
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		action.setPictureId(
					getSharedPreferences(Constants.PREF, 0)
					.getInt(Constants.SELECTED_PIC_ID, Constants.DEF_PIC_ID));
		refresh();
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		actionManager.closeDB();
	}

	private void findViews()
	{
		basicContainer = (LinearLayout) findViewById(R.id.basic_container);
		backgroundImageContainer = (LinearLayout) findViewById(R.id.background_image_container);
		
		actionPicIBtn = (ImageButton) findViewById(R.id.action_edit_pic_btn);
		actionStatusTV = (TextView) findViewById(R.id.action_edit_status);
		actionNameET = (EditText) findViewById(R.id.action_edit_name);
		actionDescriptionET = (EditText) findViewById(R.id.action_edit_description);
		actionDiceSpinner = (Spinner) findViewById(R.id.action_edit_dice);
		actionTimesSeekBar = (SeekBar) findViewById(R.id.action_edit_times);
		actionOffsetSeekBar = (SeekBar) findViewById(R.id.action_edit_offset);
		actionHasThresholdCB = (CheckBox) findViewById(R.id.action_edit_has_threshold);
		actionThresholdSeekBar = (SeekBar) findViewById(R.id.action_edit_threshold);
		
		actionSaveBtn = (Button) findViewById(R.id.action_edit_save_btn);
		actionCancelBtn = (Button) findViewById(R.id.action_edit_cancel_btn);
	}

	private void prepareViews()
	{
		basicContainer.setBackgroundColor(Setting.getBackgroundColor(this));
		backgroundImageContainer.setBackgroundResource(Setting.getBackgroundPictureId(this));
		
		if( null != backgroundImageContainer.getBackground() )
		{
			backgroundImageContainer.getBackground().setAlpha(Constants.ALPHA_BG_PIC);
		}
		
		setTitle(getText(R.string.app_name) + " " + getText(R.string.app_version_name) + " - " + getText(R.string.action_edit_title));
	
		
		actionPicIBtn.setImageResource(action.getPictureId());
		actionStatusTV.setText(action.getStatus());
		actionNameET.setText(action.getName());
		actionDescriptionET.setText(action.getDescription());
		
		//TODO so stupid method!! create a enum of Dice when have time
		String[] diceArray = getResources().getStringArray(R.array.dice_value);
		for( int i = 0; i < diceArray.length; i++ )
		{
			if ( action.getDice() == Integer.parseInt(diceArray[i]))
			{
				actionDiceSpinner.setSelection(i);
			}
		}
		
		actionTimesSeekBar.setMax(Setting.getTimesMaximum(this) - 1);
		actionTimesSeekBar.setProgress(action.getTimes() - 1);
		actionOffsetSeekBar.setMax( Setting.getOffsetMaximum(this) - Setting.getOffsetMinmum(this));
		actionOffsetSeekBar.setProgress( action.getOffset() - Setting.getOffsetMinmum(this));
		actionHasThresholdCB.setChecked( action.isHasThreshold() );
		actionThresholdSeekBar.setEnabled( action.isHasThreshold() );
		actionThresholdSeekBar.setMax( action.getDice() );
		actionThresholdSeekBar.setProgress(action.getThreshold());
	}

	private void setListeners()
	{
		actionPicIBtn.setOnClickListener(this);
		actionHasThresholdCB.setOnCheckedChangeListener(this);
		actionDiceSpinner.setOnItemSelectedListener(this);
		actionTimesSeekBar.setOnSeekBarChangeListener(this);
		actionOffsetSeekBar.setOnSeekBarChangeListener(this);
		actionThresholdSeekBar.setOnSeekBarChangeListener(this);
		
		actionSaveBtn.setOnClickListener(this);
		actionCancelBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch( v.getId() )
		{
			case R.id.action_edit_pic_btn:
				startActivity(new Intent(this, ActionPicGrid.class));
				break;
			case R.id.action_edit_cancel_btn:
				finish();
				break;
			case R.id.action_edit_save_btn:
				doSave();
				break;
		}
		
	}
	
	private void refresh()
	{
		actionPicIBtn.setImageResource(action.getPictureId());
		updateStatus();
	}
	
	private void updateStatus()
	{
		actionStatusTV.setText(action.getStatus());
	}
	
	private void doSave()
	{
		//TODO maximum text check!
		if( !TZUtils.conditionCheck(this, 
				!StringUtils.isEmpty(actionNameET.getText().toString()), 
				R.string.msg_check_text_is_empty, 
				R.string.action_edit_name))
		{
			actionNameET.requestFocus();
			return;
		}
		
		
		action.setName(actionNameET.getText().toString().trim());
		action.setDescription(actionDescriptionET.getText().toString().trim());
		
		if( action.getId() == Constants.NEW_ACTION_ID ) 	//-1
		{
			actionManager.addAction(action);
			Toast.makeText(this, R.string.msg_add_action_success, Toast.LENGTH_SHORT).show();
		}
		else
		{
			actionManager.updateAction(action);
			Toast.makeText(this, R.string.msg_upgrade_action_success, Toast.LENGTH_SHORT).show();
		}
		
		finish();
	}
	

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
	{
		switch( seekBar.getId())
		{
			case R.id.action_edit_times:
				action.setTimes( progress + 1 );
				break;
			case R.id.action_edit_offset:
				action.setOffset( progress + Setting.getOffsetMinmum(this) );
				break;
			case R.id.action_edit_threshold:
				action.setThreshold( progress );
				break;
		}
		
		updateStatus();
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar){}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar){}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		action.setHasThreshold(isChecked);
		actionThresholdSeekBar.setEnabled(isChecked);
		
		Log.i(TAG, action.toString());
		
		updateStatus();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
	{
		String selectedVal = getResources().getStringArray(R.array.dice_value)[actionDiceSpinner.getSelectedItemPosition()];
		action.setDice(Integer.parseInt(selectedVal));
		action.setThreshold(0);
		
		actionThresholdSeekBar.setProgress(action.getThreshold());
		actionThresholdSeekBar.setMax( action.getDice() );
		updateStatus();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {}
}